﻿
using System;
using System.IO;
using System.Text;

namespace TestScript
{
    public class Log
    {
        private static Log CurrentLog;

        public bool DebugEnabled = true;
        private String Name;
        private String filepath;

        public Log(String name, bool overwrite)
        {
            Name = name;
            this.filepath = "scripts/" + Name + ".log";
            CurrentLog = this;
            if (overwrite)
            {
                StreamWriter sr = null;
                sr = new StreamWriter(filepath, false);
                if (sr != null) sr.Close();
                Message(filepath + " created.");
            }
        }

        public static void Message(String msg)
        {
            CurrentLog.logImpl(String.Concat("[Message] ", msg));
        }

        public static void Warning(String msg)
        {
            CurrentLog.logImpl(String.Concat("![Warning]! ", msg));
        }

        public static void Error(String msg)
        {
            CurrentLog.logImpl(String.Concat("![Error]! ", msg));
        }

        public static void Debug(String msg)
        {
            if (!CurrentLog.DebugEnabled) return;
            CurrentLog.logImpl(String.Concat("[Debug] ", msg));
        }

        public static void Exception(System.Exception e)
        {
            StringBuilder sb = new StringBuilder(500);
            sb
            .Append("**[Exception] ")
            .Append(e.GetType().ToString())
            .Append(" ")
            .AppendLine(e.Message)
            .Append(e.StackTrace);

            CurrentLog.logImpl(sb.ToString());

            if (e.InnerException != null)
            {
                CurrentLog.logImpl("*[Info] InnerExpception found!");
                Exception(e.InnerException);
            }
        }

#pragma warning disable 0168
        private void logImpl(String content)
        {
            StreamWriter sr = null;
            try
            {
                sr = new StreamWriter(filepath, true);

                sr.WriteLine(String.Concat(DateTime.Now.ToString("yyyy/MM/dd - HH:mm:ss"), " - ", content));
            }
            catch (System.Exception ex)
            {
                if (sr != null)
                    sr.Close();
                return;
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }
#pragma warning restore 0168

    }
};